package com.rental.common.login;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.rental.common.exception.ProjectException;
import com.rental.common.result.ResultCodeEnum;
import com.rental.common.util.AuthContextHolder;
import com.rental.common.util.MyJwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Slf4j //开启日志
@Aspect //声明切面类
@Component
@Order(50) //设置优先级
@DependsOn("myJwtUtils")
public class LoginAspect {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MyJwtUtils myJwtUtils;

    @Around("execution(* com.rental.*.controller.*.*(..)) && @annotation(getIdByToken)")
    public Object process(ProceedingJoinPoint joinPoint, GetIdByToken getIdByToken) throws Throwable {
        //获取请求
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //从请求头中获取token
        String token = request.getHeader("token");

        //判断token是否为空
        if (StringUtils.isBlank(token)) throw new ProjectException(ResultCodeEnum.LOGIN_AUTH);

        //JWT为token的验证
        String s = myJwtUtils.parseToken(token);

        // UUID为token的验证
        /*
        //从redis中获取customerId
        String s = (String) redisTemplate.boundValueOps(RedisConstant.USER_LOGIN_KEY_PREFIX  + token).get();
         */

        if (StringUtils.isBlank(s)) throw new ProjectException(ResultCodeEnum.LOGIN_AUTH);
        Long customerId = Long.parseLong(s);
        //将customerId放入到当前线程的线程变量中
        AuthContextHolder.setUserId(customerId);
        return joinPoint.proceed();


    }
}
